# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10025': {  # 百合支付 支付宝红包 1.5% 100-5000 loki
        'API_KEY': 'n0rv2eg8gbd56r6ex95mwzpt64625eqk',
        'gateway': 'https://baihe.3721lily.com/Pay_Index.html',
        'query_gateway': 'https://baihe.3721lily.com/Pay_Trade_query.html',
    },
    '190561471': {  # 百合支付 支付宝红包 1.5% 100-5000 loki
        'API_KEY': '1nl9ick1p02a54n052mcjdena9gx9lva',
        'gateway': 'https://www.365lily.com/Pay_Index.html',
        'query_gateway': 'https://www.365lily.com/Pay_Trade_query.html',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


# 921 支付宝红包
def _get_pay_type(service):
    if service == 'alipay':
        return '921'
    elif service == 'alipay_new':
        return '934'
    else:
        return '934'


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info("baihepay sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    # params.pop('attach')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("baihepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('pay_memberid', app_id),
        ('pay_orderid', str(pay.id)),
        ('pay_applydate', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())),
        ('pay_bankcode', _get_pay_type(service)),
        ('pay_notifyurl', '{}/pay/api/{}/baihepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('pay_callbackurl', '{}/pay/api/{}/baihepay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('pay_amount', str(pay_amount)),
    ))
    parameter_dict['pay_md5sign'] = generate_sign(parameter_dict, api_key)
    parameter_dict['pay_productname'] = 'charge'
    _LOGGER.info("baihepay create  data: %s", json.dumps(parameter_dict))
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# OK
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("baihepay notify data1: %s, order_id is: %s", data, data['orderid'])
    _LOGGER.info("baihepay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('baihepay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['returncode'])
    trade_no = str(data['transaction_id'])
    total_fee = float(data['amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '00':
        _LOGGER.info('baihepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('pay_memberid', app_id),
        ('pay_orderid', str(pay_id)),
    ))
    parameter_dict['pay_md5sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("baihepay query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("baihepay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['trade_state'])
        trade_no = data['transaction_id']
        total_fee = float(data['amount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 'SUCCESS':
            _LOGGER.info('baihepay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('baihepay data error, status_code: %s', response.status_code)
